package cn.com.xiaoshoujia.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class XMLUtil {

    public static String map2xml(SortedMap<String, String> sortedMap) {

        return map2xml("xml", sortedMap);
    }

    public static String map2xml(String rootStr, SortedMap<String, String> sortedMap) {

        Document document = DocumentHelper.createDocument();
        Element xmlElement = document.addElement(rootStr);
        for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
            xmlElement.addElement(entry.getKey()).setText(entry.getValue());
        }

        return document.asXML();
    }

    public static SortedMap<String, String> xml2map(String xmlStr) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        try {
            List<Element> elements = DocumentHelper.parseText(xmlStr).getRootElement().elements();
            for (Element element : elements) {
                map.put(element.getName(), element.getTextTrim());
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return map;
    }
}
